package util

import (
	"encoding/json"
	"fmt"
	"path/filepath"
	"strings"
)

func ToByteArr(v interface{}) ([]byte, error) {
	jsonData, err := json.Marshal(v)
	if err != nil {
		return nil, err
	}

	return jsonData, nil
}

func ToObj(jsonData []byte, v any) error {
	err := json.Unmarshal(jsonData, &v)
	if err != nil {
		return err
	}

	return nil
}

func TrimProjectPath(fullPath, projectRoot string) string {
	relativePath, err := filepath.Rel(projectRoot, fullPath)
	if err != nil {
		// 如果出错，直接返回原路径
		return fullPath
	}
	return relativePath
}

func TransformLabels(labels string) string {
	pairs := strings.Split(labels, ",")
	result := make(map[string]string)
	for _, pair := range pairs {
		kv := strings.Split(pair, ":")
		if len(kv) == 2 {
			result[kv[0]] = kv[1]
		}
	}
	// 添加默认的 "state" 标签
	result["state"] = "up"

	// 转换为 JSON
	jsonData, err := json.Marshal(result)
	if err != nil {
		fmt.Println("JSON marshal error:", err)
		panic(err)
	}

	return string(jsonData)
}
